<template>
  <div class="app">
    <div class="content">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="300px">
        <!-- 标题 -->
        <div class="header">
          <span>服务购买</span>
        </div>

        <!-- 套餐选择 -->
        <el-form-item label="套餐名称" prop="packageId">
          <el-radio-group size="large" v-model="formData.packageId" @change="chengePackage">
            <el-radio-button
              v-for="item in jqtPackageList"
              :key="item.id"
              :label="item.id"
            >{{ item.title }}</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 套餐详情 -->
        <el-form-item v-if="selectPackage">
          <div class="package-details">
            <el-descriptions :column="2" border style="font-size: 16px; width: 800px; max-width: 900px; margin: 0 auto;">
              <el-descriptions-item label="套餐名称">{{ selectPackage.title }}</el-descriptions-item>
              <el-descriptions-item label="价格">￥{{ selectPackage.price }}</el-descriptions-item>
              <el-descriptions-item label="天数">{{ selectPackage.days }}</el-descriptions-item>
              <el-descriptions-item label="推广链接数">{{ selectPackage.spreadLinkNum }}</el-descriptions-item>
              <el-descriptions-item label="获客助手数量">{{ selectPackage.hkzsNum }}</el-descriptions-item>
              <el-descriptions-item label="企微互通数量">{{ selectPackage.htNum }}</el-descriptions-item>
              <el-descriptions-item label="小程序数量">{{ selectPackage.xcxNum }}</el-descriptions-item>
              <el-descriptions-item label="微信号数量">{{ selectPackage.wxCustomNum }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-form-item>

        <!-- 支付二维码 -->
        <el-form-item v-if="qrcodeUrl">
          <span>微信支付(扫一扫):</span>
          <div style="padding-left: 10px">
            <QrcodeVue :value="qrcodeUrl" :size="180" level="H" />
          </div>
        </el-form-item>

        <!-- 按钮区域 -->
        <div class="footer">
          <el-button
            v-if="!hasQrcode"
            :loading="buttonLoading"
            type="primary"
            @click="handleSave"
          >
            发起微信支付 ￥{{ selectPackage?.price }}
          </el-button>

          <el-button
            v-else
            type="success"
            @click="checkPayStatus"
          >
            我已支付，刷新订单
          </el-button>
        </div>

        <!-- 购买记录 -->
        <div class="purchase-records">
          <h3>购买记录</h3>
          <el-table
            :data="buyRecords"
            style="width: 100%"
            stripe
            v-loading="loading"
            size="small"
          >
            <el-table-column label="套餐名称" prop="packageName" />
            <el-table-column label="订单号" prop="orderNo" />
            <el-table-column label="购买金额" prop="price" />
            <el-table-column label="支付状态" prop="payStatus" :formatter="formatPayStatus" />
            <el-table-column label="支付完成时间" prop="payTime" :formatter="formatPayTime" />
          </el-table>

          <!-- 分页 -->
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalRecords"
            @current-change="handlePageChange"
            layout="prev, pager, next, jumper, ->, total"
          />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import QrcodeVue from 'qrcode.vue'
import { ref, onMounted, reactive } from 'vue';
import { getBuyRecord, listBuyRecord, payHtAccountByLoginUser } from '@/api/bus/buyRecord';
import { packageBuyList } from '@/api/bus/jqtPackage';
import type { JqtPackageVO } from '@/api/bus/jqtPackage/types';
import type { BuyRecordVO } from '@/api/bus/buyRecord/types';

const formRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);
const buyRecords = ref<BuyRecordVO[]>([]);
const jqtPackageList = ref<JqtPackageVO[]>([]);

const qrcodeUrl = ref("");
const serialNumber = ref("");
const buyRecordId = ref("");//购买记录的id
const hasQrcode = ref(false); // ★ 新增按钮状态控制

const formData = reactive<{ packageId: string | number | undefined }>({
  packageId: undefined,
});

const selectPackage = ref<JqtPackageVO | undefined>();

const rules = { packageId: [{ required: true, message: '请选择套餐', trigger: 'change' }] };

const getList = async () => {
  const res = await packageBuyList();
  jqtPackageList.value = res.data || [];
  if (!formData.packageId && jqtPackageList.value.length) {
    formData.packageId = jqtPackageList.value[0].id as any;
    chengePackage();
  }
};

const chengePackage = () => {
  selectPackage.value = jqtPackageList.value.find((item) => item.id == formData.packageId);
};

const getBuyRecords = async (pageNum: number, pageSize: number) => {
  loading.value = true;
  try {
    const res = await listBuyRecord({ pageNum, pageSize });
    buyRecords.value = res.rows || [];
    totalRecords.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  getBuyRecords(page, pageSize.value);
};

onMounted(() => {
  getList();
  getBuyRecords(currentPage.value, pageSize.value);
});

const handleSave = async () => {
  await formRef.value?.validate();
  if (!selectPackage.value) return;

  buttonLoading.value = true;
  qrcodeUrl.value = "";
  hasQrcode.value = false;

  const reqData = {
    id: selectPackage.value.id,
    price: selectPackage.value.price,
    days: selectPackage.value.days
  };

  try {
    const res = await payHtAccountByLoginUser(reqData);
    if (res.code == 200) {
      qrcodeUrl.value = res.data.codeUrl;
      serialNumber.value = res.data.serialNumber;
      buyRecordId.value= res.data.buyRecordId;
      hasQrcode.value = true; // ★ 出二维码后换按钮模式
      await getBuyRecords(currentPage.value, pageSize.value);
    }
  } finally {
    buttonLoading.value = false;
  }
};

// 用户点“我已支付”后手动查询状态
const checkPayStatus = async () => {

  const r = await getBuyRecord(buyRecordId.value);
  if (r.data.payStatus === 1) {
    ElMessage.success("支付成功！");
    await getBuyRecords(currentPage.value, pageSize.value);
    qrcodeUrl.value = "";
    hasQrcode.value = false;
  } else {
    ElMessage.warning("支付未完成，请稍等几秒再试");
  }
};

const formatPayStatus = (row: BuyRecordVO) => {
  switch (row.payStatus) {
    case 0: return '未支付';
    case 1: return '已支付';
    case 2: return '支付失败';
    case 3: return '退款';
    default: return '未知';
  }
};

const formatPayTime = (row: BuyRecordVO) => {
  return row.payTime ? new Date(row.payTime).toLocaleString() : '-';
};
</script>

<style scoped>
.app {
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  width: 96%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.header {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.package-details {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.purchase-records {
  margin-top: 40px;
}

.purchase-records h3 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
